#include "FileManager.h"

fileManager::fileManager(string FileName)
	:file_name(FileName)
{

}
bool fileManager::is_exist()
{
	ifstream file(file_name);
	if(!file)
		return false;
	else
		return true;
}
string fileManager::getFileName()
{
	return file_name;
}
void fileManager::add_new_line(string text)
{
	fstream file;
	file.open(file_name.c_str(),fstream::out|fstream::app);
	file<<text<<endl;
	file.close();
}

string fileManager::delte(int line_index)
{
	string deleted_line;
	
	ifstream file(file_name);

	//create a temp file
	ofstream out("new.txt");

	string temp;
	int i=0;

	//write to the temp file except the selected line
	if(file)
	{
		do
		{
			getline(file,temp);
			i++;
			if(i==line_index)
				deleted_line=temp;
			if(i!=line_index && temp!="")
				out<<temp<<endl;
		}
		while(!file.eof());
		file.close();

		//rename the new file
		remove(file_name.c_str());
		out.close();
		rename("new.txt",file_name.c_str());
	}
	return deleted_line;
}

string fileManager::get_line(int line_index)
{
	string result;
	ifstream file(file_name);
	
	if(file)
	{
		for(int i=0; i<line_index; i++)
			getline(file,result);
	}

	file.close();
	//*** need to check bugs.
	return result;
}

vector<string> fileManager::get_all_line()
{
	string temp;
	vector<string> list;

	ifstream file(file_name);
	if(file)
	{
		int n=0;
		do
		{
			n++;
			getline(file,temp);
			if(temp!="")
				list.push_back(temp);
		}
		while(!file.eof());
	}

	file.close();

	return list;
}

void fileManager::remove_file()
{
	remove(file_name.c_str());
}